package com.usian.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*@Component*/
public class LoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        boolean flag = false;
        // 请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 响应对象
        ServerHttpResponse response = exchange.getResponse();

        // 放行登录路径
        if(request.getPath().toString().contains("/login/in")){
            return chain.filter(exchange);
        }
        // 拦截： 获取一下 有没有令牌
        // 1. cookie  2. header头  3. 携带参数
        String token = request.getHeaders().getFirst("token");
        if(token == null || "".equals(token)){
            HttpCookie httpCookie =  request.getCookies().getFirst("token");
            if(httpCookie!=null){
                token =  httpCookie.getValue();
            }
            if(token == null || "".equals(token)){
                token = request.getQueryParams().getFirst("token");
            }
        }
        if(token!=null && !"".equals(token)){
            request.mutate().header("token",token);
            //放行
            return chain.filter(exchange);
        }
        //拦截
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}